# -*- coding:utf-8 -*-
import os
from everyUnitHandler.qq_2 import qqExtract
from everyUnitHandler.address_2 import addressExtract
from everyUnitHandler.email_2 import emailExtract
from everyUnitHandler.mobilphone_2 import mobelphoneNumberExtract
from everyUnitHandler.telphone_2 import IncludeSwitchNum,telphoneNumExtract,quhaoInfo
from everyUnitHandler.url_2 import urlExtract
from everyUnitHandler.weichat_2 import weichatExtract
from demo.config import domainFile
from corpusPickleHandler import readPickle

domain=readPickle(domainFile)

def qq(workdir,fileList,filenameMd5):
    target=filenameMd5+'qq.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()
        file.close()
        qqres=[]
        for line in res:
            temp=line.strip()
            if len(temp)!=0 and isNotICP(temp):
                qqres+=qqExtract(temp)
            else:
                continue
        return qqres
    else:
        return []

def address(workdir,fileList,filenameMd5):
    target=filenameMd5+'address.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()
        file.close()
        addressres=[]
        for line in res:
            if len(line.strip())!=0:
                temp=addressExtract(line)
                if temp != None:
                    addressres.append(temp)
            else:
                continue
        return addressres
    else:
        return []

def email(workdir,fileList,filenameMd5):
    target=filenameMd5+'email.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()
        file.close()
        emailres=[]
        for line in res:
            if '@' in line:
                # 由于需要处理中文域名的数据，所以处理对象需要转换成unicode编码
                emailres+=emailExtract(unicode(line))
            else:
                continue
        temp=[]
        for each in emailres:
            for onedomain in domain:
                if each.endswith(onedomain.strip()):
                    temp.append(each)
                else:
                    continue
        return temp
    else:
        return []

def mobilphone(workdir,fileList,filenameMd5):
    target=filenameMd5+'phone.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()
        file.close()
        phone=[]

        tempFlag=u''
        for line in res:
            temp=line.strip()
            # 对跨行进行处理
            # if tempFlag==u'' and temp.isdigit() and temp.startswith('1') and (len(temp)==3 or len(temp)==4):
            if tempFlag==u'' and temp.isdigit() and temp.startswith('1') and len(temp)<=5:
                tempFlag+=temp
                continue
            if tempFlag !=u'' and temp.isdigit() and len(tempFlag)<=5:
                tempFlag+=temp
                continue
            if tempFlag !=u'' and temp.isdigit():
                tempFlag+=temp
                temp=tempFlag
                tempFlag=u''

            if len(temp)!=0 and isNotICP(temp):
                phone+=mobelphoneNumberExtract(temp)
            else:
                continue
        return phone
    else:
        return []

def telphone(workdir,fileList,filenameMd5):
    target=filenameMd5+'telphone.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()
        file.close()
        telphoneres=[]
        mobilphoneres=[]

        tempFlag=u''
        tempQuhaoHaoma=u''
        tempUnionQuhaoHaoma=u''

        tempHaoma=u''
        for line in res:
            #添加跨行处理流程
            # ------------------------------------------
            line=line.strip().replace("86-",'')

            if len(line)<7:
                for key in quhaoInfo.keys():
                    if key in line:
                        tempFlag=line
                        break
                    else:
                        continue
                if tempFlag!=u'':
                    continue

            if tempFlag!=u'' and (len(line)==7 or len(line)==8):
                line=tempFlag+"*"+line
                tempFlag=u''
                tempQuhaoHaoma=line

            if tempQuhaoHaoma !=u'' and line.isdigit() and len(line)<5 and line !='86':
                line=tempQuhaoHaoma+"*"+line
                tempQuhaoHaoma=u''
            else:
                if tempQuhaoHaoma !=u'':
                    line=tempQuhaoHaoma

            if "-" in line:
                flagNum=line.count('-')
                if flagNum==1:
                    tmp=line.split('-')
                    if tmp[0].isdigit() and tmp[-1].isdigit() and len(tmp[0])<=4:
                        tempUnionQuhaoHaoma=line
                        continue

            if tempUnionQuhaoHaoma != u'' and line.isdigit() and len(line)<5 and line !='86':
                line=tempUnionQuhaoHaoma+"-"+line
                tempUnionQuhaoHaoma=u''
            else:
                if tempUnionQuhaoHaoma != u'':
                    line=tempUnionQuhaoHaoma
                    tempUnionQuhaoHaoma=u''

            if line.isdigit() and (len(line)==7 or len(line)==8):
                tempHaoma=line
                continue
            if tempHaoma != u'' and line.isdigit() and len(line)<5 and line !='86':
                line=tempHaoma+"-"+line
                tempHaoma=u''
            else:
                if tempHaoma != u'':
                    line=tempHaoma

            line=line.replace("*","-")

            # ------------------------------------------
            if len(line.strip())!=0 and isNotICP(line.strip()):
                line1=IncludeSwitchNum(line.strip())
                temp=mobelphoneNumberExtract(line1)
                if (line1.startswith('1') and line1.isdigit() and len(line1)==11):
                    mobilphoneres.append(line1)
                elif len(temp)!=0:
                    mobilphoneres+=temp
                else:
                    # 按照最新流程处理座机号
                    if len(telphoneres)!=0:
                        zhongjian=telphoneNumExtract(line1)
                        if len(zhongjian)!=0:
                            if telphoneres[-1] in zhongjian[0]:
                                del telphoneres[-1]
                                telphoneres+=zhongjian
                            else:
                                telphoneres+=zhongjian
                    else:
                        telphoneres+=telphoneNumExtract(line1)  #完成对国家码的处理
            else:
                continue


        #返回前需要对座机号进行统一处理
        quhaoFlag=None
        resultTelphone=[]

        # 是对识别结果进行二次处理
        for item in telphoneres:
            if '-' in item:
                linshi=item.split('-')
                if len(linshi[0])<=4:
                    for key,value in quhaoInfo.items():
                        if key in linshi[0] and linshi[0] in value and (len(linshi[1])==7 or len(linshi[1])==8):
                            quhaoFlag=linshi[0]
                            resultTelphone.append(item)
                            break
                else:
                    if quhaoFlag:
                        resultTelphone.append(quhaoFlag+"-"+item)
                    else:
                        resultTelphone.append(item)
            elif (len(item)==7 or len(item)==8) and quhaoFlag !=None:
                resultTelphone.append(quhaoFlag+"-"+item)
            elif len(item)==4:
                for key,value in quhaoInfo.items():
                    if key in item and item in value:
                        quhaoFlag=item
            elif len(item)==11 or len(item)==12:
                for key,value in quhaoInfo.items():
                    if key in item:
                        for oneV in value:
                            if oneV in item:
                                quhaoFlag=oneV
                                resultTelphone.append(quhaoFlag+"-"+item[len(quhaoFlag):])
                                break
                        break
            elif (len(item)==7 or len(item)==8) and quhaoFlag ==None:
                resultTelphone.append(line)
            else:
                continue
        return resultTelphone,mobilphoneres
    else:
        return [],[]

# def telphone(workdir,fileList,filenameMd5):
#     target=filenameMd5+'telphone.txt'
#     if target in fileList:
#         targetFile=os.path.join(workdir,target)
#         file=open(targetFile)
#         res=file.readlines()
#         file.close()
#         telphoneres=[]
#
#         mobilphoneres=[]
#         for line in res:
#             if len(line.strip())!=0 and isNotICP(line.strip()):
#                 line1=IncludeSwitchNum(line.strip())
#                 temp=mobelphoneNumberExtract(line1)
#                 if (line1.startswith('1') and line1.isdigit() and len(line1)==11):
#                     mobilphoneres.append(line1)
#                 elif len(temp)!=0:
#                     mobilphoneres+=temp
#                 else:
#                     # 按照最新流程处理座机号
#                     telphoneres+=telphoneNumExtract(line1)  #完成对国家码的处理
#             else:
#                 continue
#         #返回前需要对座机号进行统一处理
#         quhaoFlag=None
#         resultTelphone=[]
#
#         for item in telphoneres:
#             if '-' in item:
#                 linshi=item.split('-')
#                 for key,value in quhaoInfo.items():
#                     if key in linshi[0] and linshi[0] in value and (len(linshi[1])==7 or len(linshi[1])==8):
#                         quhaoFlag=linshi[0]
#                         resultTelphone.append(item)
#                         break
#             elif (len(item)==7 or len(item)==8) and quhaoFlag !=None:
#                 resultTelphone.append(quhaoFlag+"-"+item)
#             elif len(item)==4:
#                 for key,value in quhaoInfo.items():
#                     if key in item and item in value:
#                         quhaoFlag=item
#             elif len(item)==11 or len(item)==12:
#                 for key,value in quhaoInfo.items():
#                     if key in item:
#                         for oneV in value:
#                             if oneV in item:
#                                 quhaoFlag=oneV
#                                 resultTelphone.append(quhaoFlag+"-"+item[len(quhaoFlag):])
#                                 break
#                         break
#             else:
#                 continue
#         return resultTelphone,mobilphoneres
#     else:
#         return [],[]

def url(workdir,fileList,filenameMd5):

    target=filenameMd5+'url.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()
        file.close()
        urlres=[]
        for line in res:
            if ("http" in line or 'www' in line or "https" in line) and len(line.strip())>5:
                urlres+=urlExtract(line)
            else:
                continue
        return urlres
    else:
        return []

def weichat(workdir,fileList,filenameMd5):
    target=filenameMd5+'weichat.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()
        file.close()
        weichatres=[]

        result=[]
        stopFlag=0
        for line in res:
            line=line.strip()
            if stopFlag==1:
                if len(line)>3:
                    weichatres.append(line)
                else:
                    continue

            if len(line.strip())!=0 and isNotICP(line.strip()) and u'微信' in line:
                # weichatres+=weichatExtract(unicode(line.strip()))
                temp=weichatExtract(unicode(line.strip()))
                if len(temp)>0:
                    weichatres+=temp
                    break
                else:
                    stopFlag=1
                    continue
            else:
                continue
        # 对提取的结果进行处理
        for each in weichatres:
            item=each.strip()
            if len(item)>=3:
                item=item.replace(':','')
                result.append(item)
                return result
        return []
    else:
        return []

# 对特例模块进行处理
def otherHandle(workdir,fileList,filenameMd5):
    target=filenameMd5+'special.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()
        file.close()
        result={'email':[],'address':[],'mobilphone':[],'telphone':[],'url':[]}
        for line in res:
            each=line.strip()
            if len(each)!=0 and isNotICP(each):
                address=addressExtract(each)    #存储的是字符串类型
                url=urlExtract(each)       #存储的是列表类型
                email=emailExtract(each)    #存储的是列表类型
                mobilphone=mobelphoneNumberExtract(line)

                line1=IncludeSwitchNum(each)
                if line1.startswith('1') and line1.isdigit() and len(line1)==11:
                    mobilphone.append(line1)
                else:
                    telphone=telphoneNumExtract(line1)

                if address !=None:
                    result['address'].append(address)
                result['url']+=url
                result['email']+=email
                result['mobilphone']+=mobilphone
                result['telphone']+=telphone

            else:
                continue
        return result
    else:
        return {'email':[],'address':[],'mobilphone':[],'telphone':[],'url':[]}


def companyName(workdir,fileList,filenameMd5):
    target=filenameMd5+'companyName.txt'
    if target in fileList:
        targetFile=os.path.join(workdir,target)
        file=open(targetFile)
        res=file.readlines()

        temp=[]
        for each in res:
            temp.append(switchNum2Zhongwen(each))
        return temp
    else:
        return []


def isNotICP(string):
    if 'icp' in string or 'ICP' in string:
        return False
    else:
        return True

def switchNum2Zhongwen(each):
    return each.replace('1',u'一').replace('2',u'二').replace('3',u'三').replace('4',u'四').replace('5',u'五').replace('6',u'六').replace('7',u'七').replace('8',u'八').replace('9',u'九')
